<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            :clickModalClose="true"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="110" :rules="dynamicFormRules">
                <el-form-item label="渠道标识" v-show="isEditShow" prop="source_id">
                    <el-input v-model="formData.source_id" disabled placeholder="请输入渠道标识" id="source_id" />
                </el-form-item>
                <el-form-item label="标题" prop="title">
                    <el-input v-model="formData.title" placeholder="请输入标题" id="title" />
                </el-form-item>
                <el-form-item label="短剧标识" prop="drama_id">
                    <el-select
                        v-model="formData.drama_id"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请选择短剧"
                        :remote-method="remoteMethod"
                        @change="remoteMethod2"
                        :loading="loading"
                        style="width: 240px"
                        id="drama_id"
                    >
                        <el-option
                            v-for="item in options"
                            :key="item.drama_id"
                            :label="item.title"
                            :value="item.drama_id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="剧集标识" prop="series_id">
                    <el-select
                        v-model="formData.series_id"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请选择剧集"
                        :remote-method="remoteMethod2"
                        :loading="loading2"
                        style="width: 240px"
                        id="series_id"
                    >
                        <el-option
                            v-for="item in options2"
                            :key="item.series_id"
                            :label="(item.title ? item.title : '第'+item.sort+'集')"
                            :value="item.series_id"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="拉黑配置" prop="areas">
                    <el-input
                        v-model="formData.areas"
                        placeholder="请输入拉黑配置【区域拦截】"
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 6 }"
                        id="areas"
                    />
                </el-form-item>

                <el-form-item label="充值模板" prop="gear_type">
                    <el-select class="w-[280px]" placeholder="请选择充值模板" v-model="formData.gear_type">
                        <el-option
                            v-for="item in optionsData.articleCate"
                            :key="item.t_id"
                            :label="item.title"
                            :value="item.t_id"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="审核模式" prop="is_audit">
                    <el-radio-group v-model="formData.is_audit" id="is_audit">
                        <el-radio :label="1">审核中</el-radio>
                        <el-radio :label="0">投放中</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>


<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import {  sourceEdit, sourceAdd, sourceDetail } from '@/api/client/source'
import { drechargeGearTypeAll } from '@/api/client/recharge_gear_type'
import { dramaLists } from '@/api/client/drama'
import { seriesLists } from '@/api/client/series'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import { useDictOptions } from '@/hooks/useDictOptions'
import type { PropType } from 'vue'
const { query } = useRoute()
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑外推' : '新增外推'
})

const isEditShow = computed(() => mode.value === 'edit')

const formData = reactive({
    source_id: '',
    title: '',
    gear_type: 1,
    account_id: String(query.account_id),
    series_id: '',
    drama_id: '',
    areas: '北京|上海|沈阳|合肥|济南|青岛|广州|东莞|深圳|南京|苏州|杭州|福州|长沙|武汉|南昌|郑州|西安|赤峰|成都|腾讯|上饶|重庆|赣州',
    is_audit: 1,
})




const loading = ref(false)
const loading2 = ref(false)

const formRules = {
    source_id: [
        {
            required: true,
            message: '请输入渠道标识',
            trigger: ['blur']
        }
    ],
    title: [
        {
            required: true,
            message: '请输入配置标题',
            trigger: ['blur']
        }
    ],
    account_id: [
        {
            required: true,
            message: '请输入广告账户id',
            trigger: ['blur']
        }
    ],
    series_id: [
        {
            required: true,
            message: '请输入剧集唯一标识',
            trigger: ['blur']
        }
    ],
    drama_id: [
        {
            required: true,
            message: '请输入短剧唯一标识',
            trigger: ['blur']
        }
    ],
    areas: [
        {
            required: false,
            message: '请输入拉黑配置【区域拦截】',
            trigger: ['blur']
        }
    ],
    is_audit: [
        {
            required: true,
            message: '请输入是否为审核模式',
            trigger: ['blur']
        }
    ],
    gear_type: [
        {
            required: true,
            message: '请选择支付模板',
            trigger: ['blur']
        }
    ],
}

// 修改为动态规则
const dynamicFormRules = computed(() => {
    const rules = { ...formRules }

    // 在添加模式下，source_id 不需要必填
    if (mode.value === 'add') {
        rules.source_id = [
            {
                required: false,
                message: '请输入渠道标识',
                trigger: ['blur']
            }
        ]
    }

    return rules
})

const handleSubmit = async () => {
    await formRef.value?.validate()
    const data: any = { ...formData }
    mode.value == 'edit' ? await sourceEdit(data) : await sourceAdd(data)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = async (data: Record<string, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await sourceDetail({
        source_id: row.source_id
    })
    setFormData(data)
    remoteMethod(data.drama_title, data.drama_id)
}

interface ListItem {
    drama_id: string,
    title: string,
    sort: bigint,
}
const options = ref<ListItem[]>([])

const remoteMethod = async (query: string, drama_id: string) => {
    if (query !== '') {
        loading.value = true
        try {
            // 添加时间戳来标识当前请求
            const requestTimestamp = Date.now()
            currentRequestTimestamp = requestTimestamp

            // 正确调用API并等待结果
            const result = await dramaLists({
                title: query,
                pageSize:10
            })

            // 只有当这是最新的请求时才更新结果
            if (currentRequestTimestamp === requestTimestamp) {
                // 根据实际API响应结构调整
                options.value = result?.lists || result.lists || []
                loading.value = false

                remoteMethod2(drama_id)
            }
        } catch (error) {
            console.error('获取短剧列表失败:', error)
            options.value = []
            loading.value = false
            // 添加错误提示
            feedback.msgError('获取短剧列表失败，请重试')
        }
    }
}


// 需要在组件setup中定义
let currentRequestTimestamp = 0


interface ListItem2 {
    series_id: string,
    title: string
}
const options2 = ref<ListItem2[]>([])

const remoteMethod2 = async (query: string) => {
    if (query !== '') {
        loading2.value = true
        try {
            // 添加时间戳来标识当前请求
            const requestTimestamp2 = Date.now()
            currentRequestTimestamp2 = requestTimestamp2

            // 正确调用API并等待结果
            const result = await seriesLists({
                drama_id: query,
                pageSize:20
            })

            // 只有当这是最新的请求时才更新结果
            if (currentRequestTimestamp2 === requestTimestamp2) {
                // 根据实际API响应结构调整
                options2.value = result?.lists || result.lists || []
                loading2.value = false
            }
        } catch (error) {
            console.error('获取短剧剧集列表失败:', error)
            options2.value = []
            loading2.value = false
            // 添加错误提示
            feedback.msgError('获取短剧剧集列表失败，请重试')
        }
    }
}


// 需要在组件setup中定义
let currentRequestTimestamp2 = 0


const handleClose = () => {
    emit('close')
}

// 存储支付配置数据
const { optionsData } = useDictOptions<{
    articleCate: any[]
}>({
    articleCate: {
        api: drechargeGearTypeAll
    }
})

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
